package com.kkd.kkdapp.db.base;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import com.kkd.kkdapp.db.annotate.EADBField;
import com.kkd.kkdapp.db.annotate.EADBField.EADBFieldMode;

import android.database.Cursor;


/**
 * This class is a tool for handle field by reflect.
 * 
 * @date 2014-12-1
 * @author askzhao
 * 
 */

public class EATool {

	/**
	 * 获取带有指定注解的字段
	 * 
	 * @param cls
	 *            类
	 * @param an
	 *            指定注解
	 * @return
	 */
	public static Field[] getField(Class<?> cls, Class<? extends Annotation> an) {
		Field[] fs = cls.getFields();
		List<Field> list = new ArrayList<Field>();
		for (Field t : fs) {
			if (t.isAnnotationPresent(an)) {
				list.add(t);
			}
		}
		return list.toArray(new Field[0]);
	}

	/**
	 * 获取含有EADBField注解的字段
	 * 
	 * @param cls
	 * @return
	 */
	public static Field[] getField(Class<?> cls) {
		return getField(cls, EADBField.class);
	}

	/**
	 * 获取EADBField注解数组
	 * 
	 * @param fs
	 * @return
	 */
	public static EADBField[] getEADBField(Field[] fs) {
		EADBField[] ans = new Object() {
			public EADBField[] getAnn(Field[] fs) {
				EADBField[] ts = new EADBField[fs.length];
				for (int i = 0; i < fs.length; i++) {
					ts[i] = (EADBField) fs[i].getAnnotation(EADBField.class);
				}
				return ts;
			}
		}.getAnn(fs);
		return ans;
	}

	public static boolean isKeyField(EADBField ta) {
		EADBFieldMode[] modes = ta.mode();
		boolean isKey = false;
		for (int j = 0; j < modes.length; j++) {
			if (EADBFieldMode.Key.equals(modes[j])) {
				isKey = true;
				break;
			}
		}
		return isKey;
	}

	public static Object getValue(Cursor c, Field f, String columnName) {
		if (Integer.class.equals(f.getType()) || int.class.equals(f.getType())) {
			return c.getInt(c.getColumnIndexOrThrow(columnName));
		} else if (Long.class.equals(f.getType())
				|| long.class.equals(f.getType())) {
			return c.getLong(c.getColumnIndexOrThrow(columnName));
		} else if (Double.class.equals(f.getType())
				|| double.class.equals(f.getType())) {
			return c.getDouble(c.getColumnIndexOrThrow(columnName));
		} else if (Float.class.equals(f.getType())
				|| float.class.equals(f.getType())) {
			return c.getFloat(c.getColumnIndexOrThrow(columnName));
		} else if (String.class.equals(f.getType())) {
			return c.getString(c.getColumnIndexOrThrow(columnName));
		} else if (Short.class.equals(f.getType())
				|| short.class.equals(f.getType())) {
			return c.getShort(c.getColumnIndexOrThrow(columnName));
		} else if (Boolean.class.equals(f.getType())
				|| boolean.class.equals(f.getType())) {
			return "true".equals(c.getString(c.getColumnIndexOrThrow(columnName)));
		}
		// TODO bolb android下可以暂不支持
		return null;
	}

}
